package main

import (
	"context"
	"fmt"
	"github.com/gin-gonic/gin"
	"log"
	"net/http"
	"os"
	"os/signal"
	"sunliang.cc/middleware"
	"sunliang.cc/model"
	pkg "sunliang.cc/package"
	"sunliang.cc/routers"
	"time"
)

func init() {
	pkg.InitLogSetup()
	pkg.InitConfigSetup()
	model.DatabaseInit()
}

func main() {
	gin.SetMode(pkg.FlagConfig.Model)

	// 初始化空白Engine不附加任何中间件并加载全部的路由接口，有利于性能提升
	router := gin.New()
	router.Use(middleware.Recover(), middleware.Trace())
	if gin.Mode() == "debug" {
		router.Use(gin.Logger())
	}
	routers.LoadApiRouters(router)

	serverInit := &http.Server{
		Addr:           fmt.Sprintf(":%d", pkg.FlagConfig.Port),
		Handler:        router,
		ReadTimeout:    60 * time.Second,
		WriteTimeout:   60 * time.Second,
		MaxHeaderBytes: 1 << 20,
	}

	go func() {
		if err := serverInit.ListenAndServe(); err != nil {
			model.CloseDB()
			log.Fatalf("listen: %s", err.Error())
		}
	}()

	quit := make(chan os.Signal)
	signal.Notify(quit, os.Interrupt)
	<-quit

	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()
	if err := serverInit.Shutdown(ctx); err != nil {
		log.Fatalf("Server Shutdown: %#v", err)
	}

	log.Printf("Server exiting")
}
